import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input } from 'antd';
import { Helmet } from 'react-helmet';
import toast from 'react-hot-toast';
import { useNavigate } from 'react-router';
import { useAdminState } from '../stores/AdminStore.ts';
import { useCustomerState } from '../stores/CustomerStore.ts';
interface LoginFormValues {
  username: string;
  password: string;
}

function Login() {
  const { setCustomer } = useCustomerState();
  const { setIsAdmin } = useAdminState();
  const navigate = useNavigate();

  const onFinish = async (values: LoginFormValues) => {
    try {
      const response = await fetch('http://localhost:8000/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          customerName: values.username,
          password: values.password,
        }),
      });

      if (response.ok) {
        const data = await response.json();
        setCustomer(data.customer);
        toast.success('登录成功');
        navigate('/customer');
      } else {
        const errorData = await response.json().catch(() => ({
          message: '登录失败',
        }));
        toast.error(errorData.detail || '登录失败');
      }
    } catch (error) {
      toast.error('登录请求失败，请检查网络连接或联系管理员');
    }
  };

  const onAdminLogin = () => {
    setIsAdmin(true);
    navigate('/admin');
  };

  return (
    <>
      <Helmet>
        <html lang="zh-CN" />
        <title>登录 - SomeBank</title>
        <meta name="description" content="SomeBank登录" />
      </Helmet>
      <div className="flex flex-col items-center justify-center min-h-screen bg-gray-100">
        <div className="p-8 bg-white rounded shadow-md w-96">
          <h2 className="mb-6 text-2xl font-semibold text-center">
            SB登录页面
          </h2>
          <Form
            name="normal_login"
            className="login-form"
            initialValues={{ remember: false }}
            onFinish={onFinish}
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入客户名!' }]}
            >
              <Input
                prefix={<UserOutlined className="site-form-item-icon" />}
                placeholder="客户名"
              />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[{ required: false, message: '请输入客户密码！' }]}
            >
              <Input
                prefix={<LockOutlined className="site-form-item-icon" />}
                type="password"
                placeholder="密码"
              />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" className="w-full">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div className="absolute bottom-4 left-4">
          <Button type="link" onClick={onAdminLogin}>
            管理员登录
          </Button>
        </div>
      </div>
    </>
  );
}

export default Login;
